package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class Login extends AppCompatActivity implements View.OnClickListener {

    private EditText password;
    private EditText username;
    private CheckBox checkBox;
    private SharedPreferences config;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //
        username = findViewById(R.id.login_username);
        password = findViewById(R.id.login_password);
        checkBox = findViewById(R.id.login_checkbox);
        Button intButton = findViewById(R.id.login_int);
        Button loginbutton = findViewById(R.id.login_login);

        //按钮监听事件
        intButton.setOnClickListener(this);
        loginbutton.setOnClickListener(this);

        //记住用户名和密码
        config = getSharedPreferences("config", 0);
        String username1 = config.getString("username", null);
        String password1 = config.getString("password",null);
        if(username1 != null){
            username.setText(username1);
        }
        if(password1 != null){
            password.setText(password1);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //网络按钮
            case R.id.login_int:
                startActivity(new Intent(Login.this,Int.class));
                break;
            //登录按钮
            case R.id.login_login:
                //登录请求
                OkHttpClient okHttpClient = new OkHttpClient();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("username",username.getText());
                    jsonObject.put("password",password.getText());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                RequestBody re = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json"));
                Request build1 = new Request.Builder().post(re).url("https://mock.w2code.com/api/login").build();

                okHttpClient.newCall(build1).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String string = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Boolean verifySuccess = null;
                                try {
                                    verifySuccess = new JSONObject(string).getJSONObject("data").getBoolean("verifySuccess");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                //判断是否登录正确
                                if (verifySuccess) {
                                    Toast.makeText(Login.this,verifySuccess.toString(),Toast.LENGTH_SHORT).show();
                                    //是否记住密码
                                    if (checkBox.isChecked()){
                                        SharedPreferences.Editor edit = config.edit();
                                        edit.putString("username", String.valueOf(username.getText()));
                                        edit.putString("passssword", String.valueOf(password.getText()));
                                        edit.commit();
                                    }
                                    startActivity(new Intent(Login.this,weather.class));
                                }else {
                                    Toast.makeText(Login.this,"账号或密码输入错误，请重新输入",Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                    }
                });
                break;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(username.getWindowToken(),0);
        return super.onTouchEvent(event);
    }
}